package com.itheima.service.impl.pms;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.core.PageInfo;
import com.itheima.mapper.pms.PmsProductMapper;
import com.itheima.pojo.cms.CmsPrefrenceAreaProductRelation;
import com.itheima.pojo.cms.CmsSubjectProductRelation;
import com.itheima.pojo.pms.*;
import com.itheima.pojo.pms.vo.CreatePmsProductVo;
import com.itheima.pojo.pms.vo.SelectPmsProductVo;
import com.itheima.pojo.pms.vo.UpdateStatusVo;
import com.itheima.service.cms.CmsPrefrenceAreaProductRelationService;
import com.itheima.service.cms.CmsSubjectProductRelationService;
import com.itheima.service.pms.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
@Transactional
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements PmsProductService {

    @DubboReference
    private PmsMemberPriceService pmsMemberPriceService;

    @DubboReference
    private PmsProductAttributeValueService pmsProductAttributeValueService;

    @DubboReference
    private PmsProductFullReductionService pmsProductFullReductionService;

    @DubboReference
    private PmsProductLadderService pmsProductLadderService;

    @DubboReference
    private PmsSkuStockService pmsSkuStockService;

    @DubboReference
    private CmsSubjectProductRelationService cmsSubjectProductRelationService;

    @DubboReference
    private CmsPrefrenceAreaProductRelationService cmsPrefrenceAreaProductRelationService;

    @DubboReference
    private PmsProductVertifyRecordService pmsProductVertifyRecordService;

    /**
     * 创建商品
     * @param createPmsProductVo  接收数据实体类
     * @return
     */
    public void saveProduct(CreatePmsProductVo createPmsProductVo) {
        this.save(createPmsProductVo);
        pmsMemberPriceService.saveBatch(createPmsProductVo.getMemberPriceList());
        pmsProductAttributeValueService.saveBatch(createPmsProductVo.getProductAttributeValueList());
        pmsProductFullReductionService.saveBatch(createPmsProductVo.getProductFullReductionList());
        pmsProductLadderService.saveBatch(createPmsProductVo.getProductLadderList());
        pmsSkuStockService.saveBatch(createPmsProductVo.getSkuStockList());
        cmsSubjectProductRelationService.saveBatch(createPmsProductVo.getSubjectProductRelationList());
        cmsPrefrenceAreaProductRelationService.saveBatch(createPmsProductVo.getPrefrenceAreaProductRelationList());
    }

    /**
     * 查询商品
     * @param selectPmsProductVo
     * @return 分页查询结果
     */
    public PageInfo selectProduct(SelectPmsProductVo selectPmsProductVo) {
        //获取查询的条件
        Integer pageNum = selectPmsProductVo.getPageNum();
        Integer pageSize = selectPmsProductVo.getPageSize();
        Integer brandId = selectPmsProductVo.getBrandId();
        String keyword = selectPmsProductVo.getKeyword();
        Integer productCategoryId = selectPmsProductVo.getProductCategoryId();
        String productSn = selectPmsProductVo.getProductSn();
        Integer publishStatus = selectPmsProductVo.getPublishStatus();
        Integer verifyStatus = selectPmsProductVo.getVerifyStatus();
        //分页构造器
        Page<PmsProduct> page2 = new Page<>(pageNum,pageSize);
        //构造条件查询器
        LambdaQueryWrapper<PmsProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(brandId != null, PmsProduct::getBrandId,brandId)
                .like(keyword != null && keyword.length() !=0 , PmsProduct::getKeywords,keyword)
                .eq(productCategoryId != null, PmsProduct::getProductCategoryId,productCategoryId)
                .eq(productSn != null && productSn.length() != 0, PmsProduct::getProductSn,productSn)
                .eq(publishStatus != null, PmsProduct::getPublishStatus,publishStatus)
                .eq(verifyStatus != null,PmsProduct::getVerifyStatus,verifyStatus)
                .eq(PmsProduct::getDeleteStatus,0);

        Page<PmsProduct> productPage = this.page(page2, lqw);
        int total = (int)productPage.getTotal();
        Integer totalPage = PageInfo.totalPage(pageSize, total);

        //封装分页数据
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        pageInfo.setTotalPage(totalPage);
        pageInfo.setList(productPage.getRecords());

        return pageInfo;
    }

    /**
     * 根据商品名称或货号模糊查询
     * @param keyword
     * @return
     */
    public List<PmsProduct> likeSelect(String keyword) {
        LambdaQueryWrapper<PmsProduct> lqw = new LambdaQueryWrapper<>();
        lqw.like(keyword != null && keyword.length() !=0 , PmsProduct::getKeywords,keyword);
        List<PmsProduct> pmsProductList = this.list(lqw);
        return pmsProductList;
    }

    /**
     * 批量修改删除状态
     * @return
     */
    public void updateDeleteStatus(List<Integer> ids,Integer deleteStatus) {
        List<PmsProduct> pmsProductList = getPmsProducts(ids);

        pmsProductList = pmsProductList.stream().map(item -> {
            item.setDeleteStatus(deleteStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(pmsProductList);
    }

    /**
     * 批量设为新品
     * @param
     * @return
     */
    public void updateNewStatus(List<Integer> ids,Integer newStatus) {
        List<PmsProduct> pmsProductList = getPmsProducts(ids);

        pmsProductList = pmsProductList.stream().map(item -> {
            item.setNewStatus(newStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(pmsProductList);
    }

    /**
     *批量上下架商品
     * @param
     * @return
     */
    public void updatePublishStatus(List<Integer> ids, Integer publishStatus) {
        List<PmsProduct> pmsProductList = getPmsProducts(ids);

        pmsProductList = pmsProductList.stream().map(item -> {
            item.setPublishStatus(publishStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(pmsProductList);
    }

    /**
     *批量推荐商品
     * @param
     * @return
     */
    public void updateRecommendStatus(List<Integer> ids, Integer recommendStatus) {
        List<PmsProduct> pmsProductList = getPmsProducts(ids);

        pmsProductList = pmsProductList.stream().map(item -> {
            item.setRecommandStatus(recommendStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(pmsProductList);
    }

    /**
     *批量修改审核状态
     * @param
     * @return
     */
    public void updateVerifyStatus(List<Integer> ids, Integer verifyStatus, String detail) {

        List<PmsProduct> pmsProductList = getPmsProducts(ids);

        //修改审核状态
        pmsProductList = pmsProductList.stream().map(item -> {
            item.setVerifyStatus(verifyStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(pmsProductList);

        //向商品审核表中添加数据
        List<PmsProductVertifyRecord> vertifyRecordList =ids.stream().map(id ->{
            Long productId = Long.valueOf(id);
            PmsProductVertifyRecord vertifyRecord = new PmsProductVertifyRecord();
            vertifyRecord.setDetail(detail);
            String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            vertifyRecord.setCreateTime(nowTime);
            // TODO 添加审核人
            vertifyRecord.setStatus(verifyStatus);
            vertifyRecord.setProductId(productId);
            return vertifyRecord;
        }).collect(Collectors.toList());
        pmsProductVertifyRecordService.saveBatch(vertifyRecordList);

    }

    /**
     * 更新商品
     * @param productVo
     * @param id
     * @return
     */
    public void updateProduct(CreatePmsProductVo productVo, Integer id) {
        this.updateById(productVo);
        pmsMemberPriceService.updateBatchById(productVo.getMemberPriceList());
        pmsProductAttributeValueService.updateBatchById(productVo.getProductAttributeValueList());
        pmsProductFullReductionService.updateBatchById(productVo.getProductFullReductionList());
        pmsProductLadderService.updateBatchById(productVo.getProductLadderList());
        pmsSkuStockService.updateBatchById(productVo.getSkuStockList());
        cmsSubjectProductRelationService.updateBatchById(productVo.getSubjectProductRelationList());
        cmsPrefrenceAreaProductRelationService.updateBatchById(productVo.getPrefrenceAreaProductRelationList());
    }

    /**
     * 根据商品id获取商品编辑信息
     * @param id
     * @return
     */
    public CreatePmsProductVo getProductById(Integer id) {
        //查询商品表
        PmsProduct product = this.getById(id);

        //查询商品会员价格表
        LambdaQueryWrapper<PmsMemberPrice> memberPriceLambdaQueryWrapperlqw = new LambdaQueryWrapper<>();
        memberPriceLambdaQueryWrapperlqw.eq(PmsMemberPrice::getProductId,id);
        List<PmsMemberPrice> memberPrices = pmsMemberPriceService.list(memberPriceLambdaQueryWrapperlqw);

        //查询优选专区和产品关系表
        LambdaQueryWrapper<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationQueryWrapper = new LambdaQueryWrapper<>();
        prefrenceAreaProductRelationQueryWrapper.eq(CmsPrefrenceAreaProductRelation::getProductId,id);
        List<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelations = cmsPrefrenceAreaProductRelationService.list(prefrenceAreaProductRelationQueryWrapper);

        //查询存储产品参数信息的表
        LambdaQueryWrapper<PmsProductAttributeValue> productAttributeValueQueryWrapper = new LambdaQueryWrapper<>();
        productAttributeValueQueryWrapper.eq(PmsProductAttributeValue::getProductId, id);
        List<PmsProductAttributeValue> productAttributeValues = pmsProductAttributeValueService.list(productAttributeValueQueryWrapper);

        //查询产品满减表
        LambdaQueryWrapper<PmsProductFullReduction> productFullReductionQueryWrapper = new LambdaQueryWrapper<>();
        productFullReductionQueryWrapper.eq(PmsProductFullReduction::getProductId,id);
        List<PmsProductFullReduction> productFullReductions = pmsProductFullReductionService.list(productFullReductionQueryWrapper);

        //查询产品阶梯价格表
        LambdaQueryWrapper<PmsProductLadder> productLadderQueryWrapper = new LambdaQueryWrapper<>();
        productLadderQueryWrapper.eq(PmsProductLadder::getProductId,id);
        List<PmsProductLadder> productLadders = pmsProductLadderService.list(productLadderQueryWrapper);

        //查询sku的库存
        LambdaQueryWrapper<PmsSkuStock> skuStockQueryWrapper = new LambdaQueryWrapper<>();
        skuStockQueryWrapper.eq(PmsSkuStock::getProductId,id);
        List<PmsSkuStock> skuStocks = pmsSkuStockService.list(skuStockQueryWrapper);

        //查询专题商品关系表
        LambdaQueryWrapper<CmsSubjectProductRelation> subjectProductRelationQueryWrapper = new LambdaQueryWrapper<>();
        subjectProductRelationQueryWrapper.eq(CmsSubjectProductRelation::getProductId,id);
        List<CmsSubjectProductRelation> subjectProductRelations = cmsSubjectProductRelationService.list(subjectProductRelationQueryWrapper);


        //封装数据
        CreatePmsProductVo productVo = new CreatePmsProductVo();
        BeanUtils.copyProperties(product,productVo);
        productVo.setMemberPriceList(memberPrices);
        productVo.setPrefrenceAreaProductRelationList(prefrenceAreaProductRelations);
        productVo.setProductAttributeValueList(productAttributeValues);
        productVo.setProductFullReductionList(productFullReductions);
        productVo.setProductLadderList(productLadders);
        productVo.setSkuStockList(skuStocks);
        productVo.setSubjectProductRelationList(subjectProductRelations);

        return productVo;
    }

    /**
     *根据id查询商品信息
     * @param ids
     * @return
     */
    private List<PmsProduct> getPmsProducts(List<Integer> ids) {
        LambdaQueryWrapper<PmsProduct> lqw = new LambdaQueryWrapper<>();
        lqw.in(PmsProduct::getId, ids);
        return this.list(lqw);
    }


}
